package Question.login;

import Utils.JDBCUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

/**
 * 练习：
 * 1.通过键盘录入用户名和密码
 * 2.判断用户是否登录成功
 * 账户：zhangs   密码：123
 *
 * 注意：该练习存在sql的注入问题！
 * 1. 输入用户随便，输入密码：a' or 'a' = 'a
 * 2. sql:select * from user where username='adlfjka' and  password=a'  or   'a'   =  'a
 * 3. 拼接的字符串改变了条件
 * 解决问题参考：package JDBC.JDBCPreparedStatement.java
 *
 * @author Mc.Chai
 * @program: JavaWeb
 * @create 2021-12-14-21:05 21:05
 */
public class JDBCLogin {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String username = input.nextLine();
        System.out.println("请输入密码：");
        String password = input.nextLine();
        new JDBCLogin().login(username,password);
    }
    public boolean login(String username,String password){
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;

        try {
            if (username==null||password==null) return false;
            connection = JDBCUtils.getConnection();
            statement = connection.createStatement();
            //查询数据同时符合username和password
            String sql="select * from user where username='"+username+"' and userpwd='"+password+"'";
            resultSet = statement.executeQuery(sql);
            //判断：如果有数据则正确
            if (resultSet.next()){
                System.out.println("--登录成功！--");
                return true;
            }else{
                System.out.println("--登录失败！--");
                return false;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.close(resultSet,statement,connection);
        }
        return false;
    }
}
